package com.example.demo.service.impl;

import com.example.demo.config.SSOConfig;
import com.example.demo.model.JwtTokenContent;
import com.example.demo.model.SysUserModel;
import com.example.demo.model.base.SysUserToken;
import com.example.demo.service.ITokenService;
import com.example.demo.utils.CacheUtil;
import com.example.demo.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class ITokenServiceImpl implements ITokenService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    SSOConfig ssoConfig;
    @Override
    public SysUserToken createToken(SysUserModel sysUserModel) {
        SysUserToken sysUserToken = new SysUserToken();
        sysUserToken.setExpireTime(ssoConfig.getSessionExpire());
        sysUserToken.setToken(JwtHelper.createJwt(buildTokenData(new JwtTokenContent(sysUserModel.getSysUserId(),
                        "1", sysUserModel.getSysUserName(), "待实现功能")),
                ssoConfig.getSessionExpire(), ssoConfig.getJwtSignKey()));
        HashMap<String, String> cacheValue = new HashMap<>(4);
        cacheValue.put("userId",sysUserModel.getSysUserId());
        cacheValue.put("token",sysUserToken.getToken());
        String cacheKey = CacheUtil.UserLoginToken(sysUserModel.getSysUserId());
        redisTemplate.opsForHash().putAll(cacheKey,cacheValue);
        redisTemplate.expire(cacheKey,ssoConfig.getSessionExpire(), TimeUnit.SECONDS);

        return sysUserToken;
    }

    public Map<String, Object> buildTokenData(JwtTokenContent tokenContent) {
        Map<String, Object> dataMap = new HashMap<>(3);
        dataMap.put("userId", tokenContent.getUserId());
        dataMap.put("userType", tokenContent.getUserType());
        try {
            dataMap.put("nickName", URLEncoder.encode(tokenContent.getNickName(), "utf-8"));
            dataMap.put("realName", URLEncoder.encode(tokenContent.getRealName(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            dataMap.put("nickName", tokenContent.getNickName());
            dataMap.put("realName", tokenContent.getRealName());
        }
        return dataMap;
    }
    @Override
    public SysUserToken refreshToken(SysUserModel sysUserModel, String refreshToken) {
        return null;
    }
}
